"""
Case Type   : SQL_LIMIT
Case Name   : 设置enable_sql_limit = off，使用没有sysadmin权限的用户创建规则，合理报错
Create At   : 2025/9/16
Owner       : lonely-dance
Description :
    1、修改参数enable_sql_limit=off;
    2、创建普通用户；
    3、使用普通用户创建sql限流limit
    4、清理环境
Expect      :
    1、修改成功
    2、创建成功
    3、创建失败
    4、清理环境成功
History     :
"""

import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class SqlLimit(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----- {os.path.basename(__file__)} start-----')
        self.comm_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.Constant = Constant()
        self.limit_name1 = 'limit0006_01'

    def test_main(self):
        text = '----step1:修改参数enable_sql_limit=off expect:成功----'
        self.log.info(text)
        self.comm_sh.execute_gsguc('reload', self.Constant.GSGUC_SUCCESS_MSG, 'enable_sql_limit = off')

        text = '----step2:创建普通用户 expect:成功----'
        self.log.info(text)
        cmd = f"create user {self.limit_name1} identified by '{macro.COMMON_PASSWD}';"
        res = self.comm_sh.execut_db_sql(cmd)
        self.log.info(res)
        self.assertEqual('CREATE ROLE', res, '创建用户失败')

        text = '----step3:使用普通用户创建sql限流limit expect:合理报错----'
        self.log.info(text)
        cmd = f'''
        source {macro.DB_ENV_PATH};
        gsql -d {self.pri_node.db_name} -p {self.pri_node.db_port} -U {self.limit_name1} -W {macro.COMMON_PASSWD} -c "
        select gs_create_sql_limit('{self.limit_name1}', 'delete', 0, 100, 'now()', 
        '2025-3-30 23:59:59', '{{{{delete from}}}}', '', '');"
        '''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('ERROR:  permission denied for function must be system admin to execute', res, '报错信息异常')

    def tearDown(self):
        text = '----step4:恢复环境 expect:成功----'
        self.log.info(text)
        cmd = f"drop user if exists {self.limit_name1};"
        res = self.comm_sh.execut_db_sql(cmd)
        self.log.info(res)
        self.assertEqual('DROP ROLE', res, '执行失败' + text)
        self.log.info(f'----- {os.path.basename(__file__)} end-----')
